<template>
  <div class="box_start" v-if="start==0">
    <template v-if="show==0">
      <div class="btn" @click="start=1">自由棋局</div>
      <div class="btn" @click="start=2">玩家 VS AI</div>
      <div class="btn" @click="show=1">玩家 VS 玩家</div>
    </template>
    <template v-if="show==1">
      <input type="text" placeholder="房间号" v-model="room" />
      <input type="text" placeholder="AI接口" v-model="aiApi" />
      <div class="btn" @click="createRoom">创建房间</div>
      <div class="btn" @click="insertRoom">加入房间</div>
      <div class="btn" @click="show=0">返回</div>
    </template>
    <template v-if="show==2">等待敌方加入房间。。。</template>
  </div>
  <G_test v-if="start==1" @back="start=0"></G_test>
  <G_pve v-if="start==2" @back="start=0"></G_pve>
  <G_pvp v-if="start==3" @back="start=0" :room="room" :userId="userId" :aiApi="aiApi"></G_pvp>
</template>
<script setup>
import { onMounted, ref } from "vue";
import G_test from "./components/g_test.vue";
import G_pve from "./components/g_pve.vue";
import G_pvp from "./components/g_pvp.vue";
import axios from "./assets/axios";

//0选择页面1自由棋局
const start = ref(0);

const show = ref(0);
const room = ref('');
const aiApi = ref('');
const userId = ref('');
const createRoom = async () => {
  if (!room.value) return;
  let res = await axios.post(`/createRoom`, { room: room.value })
  console.log(res)
  if (res.code == 200) {
    userId.value = res.id;
    show.value = 2;
    setTimeout(() => {
      checkRoom();
    }, 1000);
  }
}
const checkRoom = () => {
  axios.get(`/getRoom?room=${room.value}`).then(res => {
    console.log(res)
    if (res.code == 200) {
      if(res.data.userid2){
        start.value=3;
        show.value = 0;
      }else{
        checkRoom();
      }
    }
  })
}
const insertRoom = async () => {
  if (!room.value) return;
  let res = await axios.post(`/insertRoom`, { room: room.value });
  console.log(res)
  if (res.code == 200) {
    userId.value = res.id;
    start.value=3;
    show.value = 0;
  }
}
</script>

<style lang="less" scoped>
.box_start {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .btn {
    width: 300px;
    text-align: center;
    letter-spacing: 6px;
    font-weight: bold;
    font-size: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px 14px 8px 20px;
    cursor: pointer;
    margin: 10px 0;
    box-shadow: 5px 5px 5px #999;
    background: #fff;

    &:hover {
      opacity: 0.7;
    }
  }
  input{
    width: 300px;
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: bold;
  }
}
</style>
